import multer from 'multer'
import path from 'path'
import fs from 'fs/promises'
import logger from '../services/logger.js'

// 确保目录存在
async function ensureDir(dirPath) {
  try {
    await fs.access(dirPath)
  } catch (err) {
    await fs.mkdir(dirPath, { recursive: true })
    logger.info('Created directory:', dirPath)
  }
}

const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    const tempDir = path.join(process.cwd(), 'data/temp')
    try {
      await ensureDir(tempDir)
      cb(null, tempDir)
    } catch (err) {
      logger.error('Failed to create temp directory:', err)
      cb(err)
    }
  },
  filename: (req, file, cb) => {
    // 保持原始文件名的编码
    const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8')
    cb(null, originalName)
  }
})

const fileFilter = (req, file, cb) => {
  logger.debug('Uploading file:', {
    originalname: file.originalname,
    mimetype: file.mimetype,
    headers: file.headers
  })

  const allowedTypes = [
    'text/plain',                  // .txt
    'text/markdown',               // .md
    'text/x-markdown',             // 某些系统的 .md
    'application/pdf',             // .pdf
    'application/msword',          // .doc
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
  ]

  // 检查 MIME 类型或文件扩展名
  const isAllowedMime = allowedTypes.includes(file.mimetype)
  const isMarkdown = file.originalname.toLowerCase().endsWith('.md')
  
  if (isAllowedMime || isMarkdown) {
    cb(null, true)
  } else {
    logger.warn('Invalid file type:', {
      mimetype: file.mimetype,
      filename: file.originalname
    })
    cb(new Error(`不支持的文件类型: ${file.mimetype}`), false)
  }
}

export const upload = multer({
  storage: storage,
  limits: {
    fileSize: 150 * 1024 * 1024  // 150MB
  },
  fileFilter: fileFilter
}) 